package com.mokairui.share_model__routines.protective_pause.basic;

/**
 * @Description 护型暂停模式
 * @Author Mokairui
 * @Since 2021/7/20
 */
public class GuardedObject {
    private Object response;

    /**
     * 获取结果
     */
    public Object get(long timeout) {
        synchronized (this) {
            // 开始时间
            long begin = System.currentTimeMillis();
            // 经历的时间
            long passTime = 0;
            while (response == null) {
                // 经历的时间超过了最大等待时间，推出循环
                long waitTime = timeout - passTime;
                if (waitTime < 0) { // 虚假唤醒的情况假设timeout = 2s 15:00:00 开始
                    break;
                }
                try {
                    this.wait(waitTime); // wait(timeout) 会出现虚假唤醒 15:00:1 1s 时出现虚假唤醒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passTime = System.currentTimeMillis() - begin;  // 15:00:02 1s
            }
            return this.response;
        }
    }

    public void complete(Object object) {
        synchronized (this) {
            this.response = object;
            this.notifyAll();
        }
    }
}
